<template>
  <div class="app-container">
    <CountValue
      ref="countValue"
      :ctime="ctime"
      :queryParams="queryParams"
    ></CountValue>

    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户ID" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入用户ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入用户姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邀请人id" prop="invitee">
        <el-input
          v-model="queryParams.invitee"
          placeholder="请输入邀请人id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="大区业绩" prop="regionalPerformance">
        <el-input
          v-model="queryParams.regionalPerformance"
          placeholder="请输入大区业绩"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="小区业绩" prop="communityPerformance">
        <el-input
          v-model="queryParams.communityPerformance"
          placeholder="请输入小区业绩"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分享码" prop="share">
        <el-input
          v-model="queryParams.share"
          placeholder="请输入分享码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别" prop="superior">
        <el-select
          v-model="queryParams.superior"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in superiorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="登录状态" prop="canlogin">
        <el-select
          v-model="queryParams.canlogin"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in canloginOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="类型">
        <el-select v-model="queryParams.type" clearable placeholder="请选择">
          <el-option
            v-for="item in canatmOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item label="类型">
        <el-select
          v-model="queryParams.detailed"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in detailedList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="注册时间" prop="createTime">
        <DatePicker v-model="ctime" :timevalue1="ctime"></DatePicker>
      </el-form-item>

      <el-form-item style="display: block; width: 100%">
        <div class="row">
          <div>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >

            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </div>

          <div class="operate-btn">
            <el-popover placement="bottom">
              <el-button slot="reference" plain type="primary">
                显示列设置
              </el-button>
              <div class="column-display">
                <el-checkbox-group v-model="checkedTableColumns">
                  <el-checkbox
                    v-for="column in columns"
                    :key="column.label"
                    :label="column.prop"
                  >
                    {{ column.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </el-popover>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <el-table
      ref="table"
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column prop="id" label="ID" width="100" align="center" />
      <el-table-column prop="uid" label="用户ID" width="100" align="center" />
      <el-table-column
        prop="name"
        label="转账用户名"
        width="120"
        align="center"
      />
      <el-table-column prop="detailed" label="类型" align="center" />
      <el-table-column prop="balance" label="余额" width="100" align="center" />
      <el-table-column
        label="进账/出账"
        prop="amount"
        align="center"
        width="100"
      >
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="180" align="center" />
      <el-table-column prop="createTime" label="时间" align="center" /> -->
      <el-table-column
        v-for="item in bindTableColumns"
        :key="item.label"
        align="center"
        :label="item.label"
        :prop="item.prop"
        :min-width="item.width || 100"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            type="danger"
            v-if="parseRefundBtnShow(scope.row)"
            @click="handleRefund(scope.row)"
            >退款</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  exportUser,
  fastLogin,
} from "@/api/ds/user";
import { dataQuery } from "@/api/ds/productOrder";
import { getToken } from "@/utils/auth";
import ImageUpload from "@/components/ImageUpload";
import DatePicker from "@/components/DatePicker";
import valid from "../../../utils/validator";

import {
  userTransformation,
  exportUserTransformation,
  queryYkgfc,
  refundYKGFC,
} from "@/api/ds/user";
import CountValue from "./components/CountValue.vue";
import CountValue1 from "./components/CountValue.vue";

export default {
  name: "User",
  components: {
    ImageUpload,
    DatePicker,
    CountValue,
    CountValue1,
  },
  data() {
    return {
      ctime: [], //搜索框 时间选择器数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        openid: null,
        nickName: null,
        avatarImage: null,
        userName: null,
        password: null,
        gender: null,
        share: null,
        idCard: null,
        bankNo: null,
        superior: null,
        invitee: null,
        inviteeSuperior: null,
        createTime: null,
        phone: null,
        realName: null,
        address: null,
        quota: null,
        balanceQuota: null,
        cash: null,
        status: null,
        type: null,
        detailed: null,
        canlogin: null,
        regionalPerformance: null, // 大区业绩
        communityPerformance: null, // 小区业绩
      },
      // 表单参数
      form: {},
      superiorOptions: [
        // 级别下拉框
        { value: "0", label: "游客" },
        { value: "1", label: "一级" },
        { value: "2", label: "二级" },
      ],
      canatmOptions: [
        { value: "转换", label: "转换" },
        { value: "转账", label: "转账" },
        { value: "提现", label: "提现" },
      ],
      detailedList: [
        { value: "转换", label: "转换" },
        { value: "转账", label: "转账" },
        { value: "提现YKGFC地址", label: "提现" },
      ],
      canloginOptions: [
        { value: 1, label: "可登陆" },
        { value: 2, label: "不可登陆" },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        share: [{ required: true, message: "分享码不能为空", trigger: "blur" }],
        phone: [
          {
            required: true,
            validator: valid.telphone,
            message: "",
            trigger: ["change", "blur"],
          },
        ],
      },
      productList: [], // 产品数据
      iframeSrc: "",
      clientOpen: false,
      clientSrc: "",

      columns: [
        { label: "ID", prop: "id", width: 60, show: true },
        { label: "用户ID", prop: "uid", width: 50, show: true },
        { label: "转账用户名", prop: "name", width: 100, show: true },
        { label: "类型", prop: "detailed", width: 150, show: true },
        { label: "进账/出账", prop: "amount", width: 100, show: true },
        { label: "余额", prop: "balance", width: 80, show: true },
        { label: "备注", prop: "remark", width: 120, show: true },
        { label: "时间", prop: "createTime", width: 120, show: true },
        { label: "转换价格", prop: "marketValue", width: 50, show: true },
      ],
    };
  },
  computed: {
    parseRefundBtnShow() {
      return (item) => {
        if (item.detailed.indexOf("提现YKGFC地址") !== -1) {
          return true;
        } else {
          return false;
        }
      };
    },
    formatNumber() {
      return (num) => {
        if (num) {
          num = num + "";
          let index = num.indexOf(".");
          if (index !== -1) {
            num = num.substring(0, 2 + index + 1);
          } else {
            num = num.substring(0);
          }
          return parseFloat(num).toFixed(2);
        } else {
          return "0.00";
        }
      };
    },

    bindTableColumns() {
      return this.columns.filter((column) => column.show);
    },
    checkedTableColumns: {
      get() {
        return this.bindTableColumns.map((column) => column.prop);
      },
      set(checked) {
        // 设置表格列的显示与隐藏
        this.columns.forEach((column) => {
          // 如果选中，则设置列显示
          if (checked.includes(column.prop)) {
            column.show = true;
          } else {
            // 如果未选中，则设置列隐藏
            column.show = false;
          }
        });
      },
    },
  },
  created() {
    this.iframeSrc = `http://data.web.gtfy.net.cn/#/`;
    // this.getProductData();
    this.getList();
  },
  beforeUpdate() {
    this.$nextTick(() => {
      // 在数据加载完，重新渲染表格
      this.$refs.table.doLayout();
    });
  },

  mounted() {
    this.statusQuery();
  },
  methods: {
    async handleRefund(item) {
      let res = await refundYKGFC({ id: item.id });
      console.log(res);
      if (res.code === 200) {
        this.$message({
          type: "success",
          message: res.msg,
        });

        this.getList();
      }
    },
    // 查看团队
    async checkGroup(row) {
      let uid = row.uid;
      let res = await fastLogin(uid);
      if (res.code === 200) {
        let token = res.data.token;
        // 显示
        this.$refs.enterCheckTeam.token = token;
        this.$refs.enterCheckTeam.show = true;
      }
    },

    updatecan(row, type, status) {
      var data = {};
      if (type == "canlogin") {
        data.canlogin = status;
      } else {
        data.type = status;
      }
      updateUser(data).then((response) => {
        this.msgSuccess("更新成功");

        this.getList();

        this.statusQuery();
      });
    },
    /** 是否可登陆 */
    canLogin(e, row) {
      row.canlogin = e;
      updateUser(row).then((response) => {
        this.msgSuccess("更新成功");
        this.getList();
        this.statusQuery();
      });
    },
    /** 是否可提现 */
    canAtm(e, row) {
      // let data = { canlogin: e , id : id}
      row.type = e;
      updateUser(row).then((response) => {
        this.msgSuccess("更新成功");
        this.getList();
        this.statusQuery();
      });
    },
    /** 查询积分贡献值累计释放 */
    getProductData() {
      dataQuery().then((response) => {
        this.productList = JSON.parse(JSON.stringify(response)).data;
        this.loading = false;
        this.show = true;
      });
    },
    /** 查询用户信息列表 */
    async getList() {
      this.loading = true;

      let q = this.addDateRange(this.queryParams, this.ctime, "");

      //   listUser(q).then((response) => {
      //     this.userList = response.rows;
      //     this.total = response.total;
      //     this.loading = false;
      //   });
      let res = await userTransformation(q);

      if (res.code === 200) {
        this.userList = res.rows;
        this.total = res.total;
      }

      this.loading = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
        openid: null,
        nickName: null,
        avatarImage: null,
        userName: null,
        password: null,
        gender: null,
        share: null,
        superior: null,
        invitee: null,
        inviteeSuperior: null,
        phone: null,
        realName: null,
        address: null,
        quota: null,
        balanceQuota: null,
        cash: null,
        status: 0,
        remark: null,
        createTime: null,
        type: null,
        canlogin: null,
        detailed: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();

      this.statusQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      (this.ctime = []), this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.uid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 冻结or提现 */
    updateInfo(row, type) {
      this.$confirm("此操作将修改状态, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        if (type == "1") {
          // 冻结
          this.canLogin("2", row.uid);
        } else if (type == "2") {
          //提现
          this.canAtm("2", row.uid);
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const uid = row.uid || this.ids;
      getUser(uid).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.uid != null) {
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();

              this.statusQuery();
            });
          } else {
            addUser(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();

              this.statusQuery();
            });
          }
        }
      });
    },
    /** 一键登录按钮操作 */
    handleDelete(row) {
      const uid = row.uid || this.ids;
      this.$confirm('是否一键登录"' + row.userName + '"此用户', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        fastLogin(uid).then((res) => {
          if (res.code === 200) {
            let token = res.data.token;
            // this.iframeSrc = `http://data.web.gtfy.net.cn/#/?token=${token}`;
            this.iframeSrc = `http://test.web.rfnpbag.cn/#/?token=${token}`;
            this.clientOpen = true;
          }
        });
      });
    },
    async statusQuery() {
      // let q1 = this.addDateRange(this.queryParams, this.ctime, "");
      // q1.detailed = "转换";
      // let res = await queryYkgfc(q1);
      // if (res.code === 200) {
      //   this.totalTransformation = res.rows[0];
      // }

      // let q2 = this.addDateRange(this.queryParams, this.ctime, "");
      // q2.detailed = "转账";
      // let res2 = await queryYkgfc(q2);
      // if (res2.code === 200) {
      //   this.totalZhuanzhang = res2.rows[0];
      // }

      // let q3 = this.addDateRange(this.queryParams, this.ctime, "");
      // q3.detailed = "提现";
      // let res3 = await queryYkgfc(q3);
      // if (res3.code === 200) {
      //   this.totalTixian = res3.rows[0];
      // }

      // let q4 = this.addDateRange(this.queryParams, this.ctime, "");
      // q4.detailed = null;

      // let res4 = await queryYkgfc(q4);
      // if (res4.code === 200) {
      //   this.totalValue = res4.rows[0];
      // }

      this.$refs.countValue.statusQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有YKGFC数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUserTransformation(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>

<style scoped>
.row {
  width: 88vw;
  min-width: 80vw;
  display: flex;
  flex-flow: row nowrap;

  justify-content: flex-start;
  align-items: center;
}
.column-options {
  width: 1500px;
  margin: 50px auto;
}
.column-display {
  width: 180px;
}
.operate-btn {
  padding: 0 15px;
  text-align: right;
  justify-self: flex-end;
  flex: 1;
}

.el-form-item {
  margin-bottom: 0.5%;
}
.flex {
  display: flex;
  align-items: center;
}

.columm {
  width: 100%;
  color: #333333;
  font-weight: 600;
  padding: 20px;

  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: center;
}
.el-icon-check {
  font-size: 24px;
  color: green;
}
.el-icon-close {
  font-size: 24px;
  color: red;
}
.titleClass {
  background: lightgray;
  text-align: center;
  font-size: 18px;
  padding: 1%;
}
.titleContentClass {
  text-align: center;
  color: red;
  border: 1px solid lightgray;
  font-size: 18px;
  padding: 1%;
}
</style>
